import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux, Link } from "dva/router";
import { Form, Input, Button, Row, Col, Popover, Progress, Alert } from "antd";
import styles from "./index.less";
import request from "../../utils/request";

const FormItem = Form.Item;

const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  pool: <div className={styles.error}>强度：太短</div>
};

const passwordProgressMap = {
  ok: "success",
  pass: "normal",
  pool: "exception"
};

@connect(({ global }) => {
  return { 服务器接口地址: global.服务器接口地址 };
})
@Form.create()
export default class Register extends Component {
  state = {
    confirmDirty: false,
    visible: false,
    help: "",
    验证码Id: "",
    错误信息: "",
    正在注册: false
  };

  componentDidMount = () => {
    this.获取验证码();
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.服务器接口地址 && !this.state.验证码Id) {
      this.获取验证码();
    }
  }

  获取验证码 = () => {
    request("用户/验证码", {}, 验证码Id => {
      this.setState({ 验证码Id });
    });
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue("密码");
    if (value && value.length > 9) {
      return "ok";
    }
    if (value && value.length > 5) {
      return "pass";
    }
    return "pool";
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        this.setState({ 正在注册: true });
        request(
          "用户/注册",
          { ...values, 验证码Id: this.state.验证码Id },
          res => {
            this.setState({ 错误信息: "", 正在注册: false });
            dispatch(routerRedux.push("/login"));
          },
          (code, res) => {
            this.setState({ 错误信息: res, 正在注册: false });
            this.获取验证码();
          }
        );
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue("密码")) {
      callback("两次输入的密码不匹配!");
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    if (!value) {
      this.setState({
        help: "请输入密码！",
        visible: !!value
      });
      callback("error");
    } else {
      this.setState({
        help: ""
      });
      if (!this.state.visible) {
        this.setState({
          visible: !!value
        });
      }
      if (value.length < 6) {
        callback("error");
      } else {
        const { form } = this.props;
        if (value && this.state.confirmDirty) {
          form.validateFields(["confirm"], { force: true });
        }
        callback();
      }
    }
  };
  检测用户名 = (rule, value, callback) => {
    if (!value) {
      callback();
    } else {
      request("用户/检测用户名", { 用户名: value }, 不存在 => {
        if (不存在) {
          callback();
        } else {
          callback("用户名已存在");
        }
      });
    }
  };

  renderPasswordProgress = () => {
    const { form } = this.props;
    const value = form.getFieldValue("密码");
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  render() {
    const { form, 服务器接口地址 } = this.props;
    const { getFieldDecorator } = form;
    const { 验证码Id, 错误信息, 正在注册 } = this.state;
    return (
      <div className={styles.main}>
        <Form onSubmit={this.handleSubmit}>
          {错误信息 && (
            <Alert
              style={{ marginBottom: 24 }}
              message={错误信息}
              type="error"
              showIcon
            />
          )}
          <FormItem>
            {getFieldDecorator("用户名", {
              rules: [
                {
                  required: true,
                  message: "请输入用户名！"
                },
                {
                  validator: this.检测用户名
                }
              ]
            })(<Input size="large" placeholder="用户名" />)}
          </FormItem>
          <FormItem help={this.state.help}>
            <Popover
              content={
                <div style={{ padding: "4px 0" }}>
                  {passwordStatusMap[this.getPasswordStatus()]}
                  {this.renderPasswordProgress()}
                  <div style={{ marginTop: 10 }}>
                    请至少输入 6 个字符。请不要使用容易被猜到的密码。
                  </div>
                </div>
              }
              overlayStyle={{ width: 240 }}
              placement="right"
              visible={this.state.visible}
            >
              {getFieldDecorator("密码", {
                rules: [
                  {
                    validator: this.checkPassword
                  }
                ]
              })(
                <Input
                  size="large"
                  type="password"
                  placeholder="至少6位密码，区分大小写"
                />
              )}
            </Popover>
          </FormItem>
          <FormItem>
            {getFieldDecorator("confirm", {
              rules: [
                {
                  required: true,
                  message: "请确认密码！"
                },
                {
                  validator: this.checkConfirm
                }
              ]
            })(<Input size="large" type="password" placeholder="确认密码" />)}
          </FormItem>
          <FormItem>
            <Row gutter={8}>
              <Col span={16}>
                {getFieldDecorator("验证码", {
                  rules: [
                    {
                      required: true,
                      message: "请输入验证码！"
                    }
                  ]
                })(<Input size="large" placeholder="验证码" />)}
              </Col>
              <Col span={8}>
                <Button
                  size="large"
                  className={styles.getCaptcha}
                  onClick={this.获取验证码}
                >
                  <img
                    src={
                      "http://" +
                      服务器接口地址 +
                      "/验证码图片/" +
                      验证码Id +
                      ".png"
                    }
                    alt="点击刷新"
                  />
                </Button>
              </Col>
            </Row>
          </FormItem>
          <FormItem>
            {getFieldDecorator("邮箱", {
              rules: [
                {
                  type: "email",
                  message: "邮箱地址格式错误！"
                }
              ]
            })(<Input size="large" placeholder="邮箱 (用于找回密码)" />)}
          </FormItem>
          <FormItem>
            <Button
              size="large"
              loading={正在注册}
              className={styles.submit}
              type="primary"
              htmlType="submit"
            >
              注册
            </Button>
            <Link className={styles.login} to="/login">
              使用已有账户登录
            </Link>
          </FormItem>
        </Form>
      </div>
    );
  }
}
